#include "CamerasManager.h"

CamerasManager::CamerasManager(void)
{
}

CamerasManager::~CamerasManager(void)
{
	std::map<std::string, Camera*>::iterator i;
	for (i = cameras.begin(); i != cameras.end(); i++)
		delete (*i).second;
	
	cameras.clear();
}

void CamerasManager::ReadFile(const char *filename)
{
	std::ifstream file(filename, std::ios::binary);

	int id;
	file.read((char*)&id, sizeof(int));

	while (id != 0)
	{
		int targetId;
		file.read((char*)&targetId, sizeof(int));

		Camera *camera = new Camera(id, targetId);

		BYTE nameSize;
		file.read((char*)&nameSize, sizeof(BYTE));
		char *name = new char[nameSize + 1];
		name[nameSize] = 0;
		file.read(name, nameSize);

		Add(name, camera);

		file.read((char*)&id, sizeof(id));
	}		

	file.close();
}

void CamerasManager::Load(const char *path, const char *ext)
{
	std::string searchPath = path;
	searchPath += "\\*.";
	searchPath += ext;

	WIN32_FIND_DATA fd;

	HANDLE hfile = FindFirstFile(searchPath.c_str(), &fd);
	if (hfile != INVALID_HANDLE_VALUE)
	{
		BOOL doSearch = true;
		while (doSearch)
		{
			std::string camPath = path;
			camPath += "\\";
			camPath += fd.cFileName;

			ReadFile(camPath.c_str());

			doSearch = FindNextFile(hfile, &fd);
		}

		FindClose(hfile);
	}
}

Camera * CamerasManager::Get(const char *name)
{
	std::map<std::string, Camera*>::iterator i = cameras.find(name);
	if (i == cameras.end())
		return NULL;

	return (*i).second;
}

void CamerasManager::Add(const char *name, Camera *camera)
{
	this ->cameras[name] = camera;
}

int CamerasManager::GetCount()
{
	return (int)cameras.size();
}

void CamerasManager::Get(int i, char *name, Camera *&res)
{
	std::map<std::string, Camera*>::iterator it = cameras.begin();
	while (i--)
		it ++;

	strcpy(name, (*it).first.c_str());
	res = (*it).second;
}
